/**
 *   获取node命令行参数
 */
function getEnvParams(options) {
  const envParams = {}
  // 从第三个参数开始,是自定义参数
  for (let i = 2, len = options.length; i < len; i++) {
    const arg = options[i].split('=')
    envParams[arg[0]] = arg[1]
  }
  return envParams
}

console.log('运行miniprogram-ci')

const ci = require('miniprogram-ci')

const { type, version = '', desc = '', appid = '', buildId = '' } = getEnvParams(process.argv)

if (!appid) {
  console.error('appid不能为空!!!')
  process.exit(1)
}

// 微信小程序的私有key文件存储路径,每次新增appid时,需要找运维加私有key
const privateKeyPath = `/root/.jenkins/cert/private.${appid}.key`

// 请求参数
const reqParams = {
  appid,
  type: 'miniProgram',
  projectPath: './',
  privateKeyPath,
  ignores: ['node_modules/**/*', 'yarn.lock', '.*']
}

const uploadParams = {
  es6: false, //  "es6 转 es5"
  es7: false, // "增强编译"
  minify: true, // "样式自动补全"
  codeProtect: false, // "代码保护"
  autoPrefixWXSS: false // "样式自动补全"
}

const project = new ci.Project({ ...reqParams })

if (type === 'preview' || type === 'publish') {
  (async () => {
    const previewResult = await ci.preview({
      project,
      desc: '预览', // 此备注将显示在“小程序助手”开发版列表中
      setting: uploadParams,
      qrcodeFormat: 'image',
      qrcodeOutputDest: `./qrcode-${buildId}.jpg`,
      onProgressUpdate: console.log
      // pagePath: 'pages/index/index', // 预览页面
      // searchQuery: 'a=1&b=2',  // 预览参数 [注意!]这里的`&`字符在命令行中应写成转义字符`\&`
    })
    console.log(previewResult)
  })()
}

if (type === 'publish') {
  (async () => {
    const uploadResult = await ci.upload({
      project,
      version,
      desc,
      setting: uploadParams,
      onProgressUpdate: console.log
    })
    console.log(uploadResult)
  })()
}
